package org.csu.mypetstore_seller.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.servlet.http.HttpSession;
import org.csu.mypetstore_seller.domain.Item;
import org.csu.mypetstore_seller.domain.Product;
import org.csu.mypetstore_seller.persistence.ItemMapper;
import org.csu.mypetstore_seller.persistence.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.WebRequest;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.util.List;


@Controller
@Slf4j
@RequestMapping("catalog")
public class ProductController {
    @Autowired
    ItemMapper itemMapper;//商品库存

    @Autowired
    ProductMapper productMapper;//商品数据库

    //
    @GetMapping("product*")
    private String product(@ModelAttribute Product product1, Model model, HttpSession session){
        log.info("查看商品详情，商品ID：{}", product1.getProductId());
        
        Product product = productMapper.selectById(product1.getProductId());
        if (product == null) {
            log.warn("未找到商品信息，商品ID：{}", product1.getProductId());
            return "catalog/error";
        }

        //查询该商品下的所有库存项
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("productid",product.getProductId());
        List<Item> items = itemMapper.selectList(queryWrapper);
        log.info("商品{}的库存项数量：{}", product.getProductId(), items.size());

        //将数据传递给前端
        model.addAttribute("items",items);
        session.setAttribute("productId",product.getProductId());
        model.addAttribute("product",product);
        return "catalog/product.html";
    }

    @PostMapping("/addItem")
    public String addItem(Model model, HttpSession session, WebRequest request) {
        // 获取参数
        String itemId = request.getParameter("itemId");
        String productId = request.getParameter("productId");
        String listPriceStr = request.getParameter("listPrice");
        String unitCostStr = request.getParameter("unitCost");
        String supplierStr = request.getParameter("supplier");
        String status = request.getParameter("status");
        String attr1 = request.getParameter("attr1");
        String attr2 = request.getParameter("attr2");
        String attr3 = request.getParameter("attr3");
        String attr4 = request.getParameter("attr4");
        String attr5 = request.getParameter("attr5");
        String amountStr = request.getParameter("amount");

        // 校验参数是否为空
        if (itemId == null || itemId.trim().isEmpty() ||
                productId == null || productId.trim().isEmpty() ||
                listPriceStr == null || listPriceStr.trim().isEmpty() ||
                unitCostStr == null || unitCostStr.trim().isEmpty() ||
                supplierStr == null || supplierStr.trim().isEmpty() ||
                status == null || status.trim().isEmpty() ||
                amountStr == null || amountStr.trim().isEmpty()) {
            throw new IllegalArgumentException("所有字段都必须填写");
        }

        // 校验 productId 是否存在

        Product product = productMapper.selectById(productId);
        if (product == null) {
            throw new IllegalArgumentException("商品ID不存在");
        }

         //校验 itemId 是否唯一
         Item existingItem = itemMapper.selectById(itemId);
        if (existingItem != null) {
            throw new IllegalArgumentException("库存项ID已存在");
        }

        // 转换并校验数值类型
        float listPrice;
        float unitCost;
        int supplier;
        int amount;
        try {
            listPrice = Float.parseFloat(listPriceStr);
            unitCost = Float.parseFloat(unitCostStr);
            supplier = Integer.parseInt(supplierStr);
            amount = Integer.parseInt(amountStr);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("数值格式错误");
        }

        // 校验 amount 是否为非负数
        if (amount < 0) {
            throw new IllegalArgumentException("库存数量不能为负数");
        }
        System.out.println(supplier);
        // 创建 Item 对象
        Item item = new Item();
        item.setItemId(itemId);
        item.setProductId(productId);
        item.setListPrice(BigDecimal.valueOf(listPrice));
        item.setUnitCost(BigDecimal.valueOf(unitCost));
        item.setSupplierId(supplier);
        item.setStatus(status);
        item.setAttribute1(attr1);
        item.setAttribute2(attr2);
        item.setAttribute3(attr3);
        item.setAttribute4(attr4);
        item.setAttribute5(attr5);
        item.setAmount(amount);

        log.info("准备添加新的商品库存项：{}", item);

        // 插入 Item
        try {
            itemMapper.insert(item);
            log.info("商品库存项添加成功，商品ID：{}，库存项ID：{}", productId, itemId);
        } catch (Exception e) {
            log.info("商品库存项失败，商品ID：{}，库存项ID：{}", productId, itemId);
            throw new IllegalArgumentException("添加库存项失败，请稍后重试");
        }

        // 加载更新后的数据
        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("productid", productId);
        List<Item> items = itemMapper.selectList(queryWrapper);
        model.addAttribute("items", items);
        session.setAttribute("productId", productId);
        //Product product = productMapper.selectById(productId);
        model.addAttribute("product", product);
        log.info("商品{}的库存列表已更新，当前库存项数量：{}", productId, items.size());

        return "catalog/product"; // 返回商品页面
    }
//    @PostMapping("addItem*")
//    private String addItem(Model model, HttpSession session, WebRequest request){
//        String itemId = request.getParameter("itemId");
//        String productId = request.getParameter("productId");
//        float listPrice = Float.parseFloat(request.getParameter("listPrice"));
//        float unitCost = Float.parseFloat(request.getParameter("unitCost"));
//        int supplier = Integer.parseInt(request.getParameter("supplier"));
//        String status = request.getParameter("status");
//        String attr1 = request.getParameter("attr1");
//        String attr2 = request.getParameter("attr2");
//        String attr3 = request.getParameter("attr3");
//        String attr4 = request.getParameter("attr4");
//        String attr5 = request.getParameter("attr5");
//        int amount = Integer.parseInt(request.getParameter("amount"));
//
//        //创建item对象
//        Item item = new Item();
//        item.setItemId(itemId);
//        item.setProductId(productId);
//        item.setListPrice(BigDecimal.valueOf(listPrice));
//        item.setUnitCost(BigDecimal.valueOf(unitCost));
//        item.setSupplierId(supplier);
//        item.setStatus(status);
//        item.setAttribute1(attr1);
//        item.setAttribute2(attr2);
//        item.setAttribute3(attr3);
//        item.setAttribute4(attr4);
//        item.setAttribute5(attr5);
//        item.setAmount(amount);
//        log.info("准备添加新的商品库存项：{}", item);
//
//        System.out.println(item);
//
//        itemMapper.insert(item);
//        log.info("商品库存项添加成功，商品ID：{}，库存项ID：{}", productId, itemId);
//
//        //加载更新后的数据
//        QueryWrapper queryWrapper = new QueryWrapper();
//        queryWrapper.eq("productid",productId);
//        List<Item> items = itemMapper.selectList(queryWrapper);
//        model.addAttribute("items",items);
//        session.setAttribute("productId",productId);
//        Product product = productMapper.selectById(productId);
//        model.addAttribute("product",product);
//        log.info("商品{}的库存列表已更新，当前库存项数量：{}", productId, items.size());
//        return "catalog/product.html";
//    }
}
